import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.zbcz.crm.bean.InnerListBean
import com.zbcz.crm.databinding.ItemVisitListContentBinding
import com.zbcz.crm.databinding.ItemVisitListContentFollowerBinding

class InnerListAdapter : ListAdapter<InnerListBean, RecyclerView.ViewHolder>(DiffCallback()) {

    companion object {
        const val TYPE_NORMAL = 0
        const val TYPE_FOLLOWER = 1
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        val inflater = LayoutInflater.from(parent.context)
        return if (viewType == TYPE_NORMAL) {
            val binding = ItemVisitListContentBinding.inflate(inflater, parent, false)
            InnerListHolder(binding)
        } else {
            val binding = ItemVisitListContentFollowerBinding.inflate(inflater, parent, false)
            InnerListFlowerHolder(binding)
        }
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        val item = getItem(position)
        if (holder is InnerListHolder) {
            holder.bind(item)
        } else if (holder is InnerListFlowerHolder) {
            holder.bind(item)
        }
    }

    override fun getItemViewType(position: Int): Int {
        return if (!getItem(position).followName.isNullOrEmpty()) {
            TYPE_FOLLOWER
        } else {
            TYPE_NORMAL
        }
    }

    inner class InnerListHolder(private val binding: ItemVisitListContentBinding) :
        RecyclerView.ViewHolder(binding.root) {

        fun bind(item: InnerListBean) {
            binding.tvTitle.text = item.title
            binding.tvContent.text = item.content
            binding.viewDivider.visibility = if (adapterPosition == itemCount - 1) View.GONE else View.VISIBLE
        }
    }

    inner class InnerListFlowerHolder(private val binding: ItemVisitListContentFollowerBinding) :
        RecyclerView.ViewHolder(binding.root) {

        fun bind(item: InnerListBean) {
            binding.tvTitle.visibility = if (item.isFirstFollower) View.VISIBLE else View.GONE
            binding.tvContent.text = item.followName
            binding.tvFollowerEmployee.text = item.followEmployer
            binding.tvFollowerPhone.text = item.followMobileNo
            binding.viewDivider.visibility = if (adapterPosition == itemCount - 1) View.GONE else View.VISIBLE
        }

    }

    class DiffCallback : DiffUtil.ItemCallback<InnerListBean>() {
        override fun areItemsTheSame(oldItem: InnerListBean, newItem: InnerListBean): Boolean {
            return oldItem.title == newItem.title
        }

        override fun areContentsTheSame(oldItem: InnerListBean, newItem: InnerListBean): Boolean {
            return oldItem == newItem
        }
    }
}
